<?php

/**
  内蒙古K3投注购彩
 */

namespace McWin\Controller;
use Common\Controller\HomebaseController;
// use McUser\Model\KkkUserModel;

// load("@.myfunc");

class NmgK3BuyController extends HomebaseController {

	function _initialize(){}

	/**
	 *  读取赔率数据.
	 *	nmg_k3: 内蒙古快3
	 *  bj_cars: 北京赛车
	 *
	 */		

	/**
	 * @return 内蒙古K3, 购彩	 
	 * 
	 */
	public function order(){		
		$type = $_POST['type'];
		$qishu = $_POST['qishu'];		// 传过来的期数. 要和服务器计算的期数做对比, 如果不对, 则不能购彩.
		$list = $_POST['list'];

		$userID = $_POST['userID'];
		$token = $_POST['token'];

		// 注单 列表
		if ( $type != 'nmg_k3' || $list == '' ){			
			$this->return_data_error('-2') ;
			return;
		}

		// 用户名 和 密码
		// if ($userID == '' || $token == '' ){			
		// 	$this->return_data_error('-2') ;
		// 	return;
		// }else{
		// 	if($this -> compare_token($userID, $token) === false){
		// 		return;
		// 	}
		// }

		// 去掉空的注单.
		$list = array_filter($list);
		$names = array_keys($list);

		// 返回的数据.
		$result['type'] = $type;
		$game_name = '内蒙古快3';
		$result['game_name'] = $game_name;
		$result['qishu'] = $qishu;

		$d_odds = D('NmgK3Odds');
		$d_cost_money = D('McUser/KkkUser');
		$d_up_limit = D('NmgK3UpLimit');
		$d_bet = D('CccBet');
		$d_open = D('NmgK3Open');
		$g_up_limit = D('KkkGroup');

		// 注单格式
		$resultList = array();
		 // array('wanfa' => '',
			// 'wanfa_xx' => '',			// 玩法详细.
			// 'money' => 0,
			// 'odds' => 0,
			// 'win' => 0);

		// 总共花费金额.
		$allmoney = 0;

		{	    
		    // 获取期数
		    // 1. ----------------------------- 根据时间来计算期数, 如果期数不对, 则不进行购彩操作 -----------------------
		    // $qishu_s  = lottery_qishu_s_6($_REQUEST['type']);

		    // 第一次开奖和最后一次开奖, 每天73期, 09:45起每10分钟一期
		    $open_time  = strtotime(date("Y-m-d") . ' 09:35:00');
		    $close_time = strtotime(date("Y-m-d") . ' 22:05:00');
		    
		    $first_q_num = date("Ymd") . '001';
		    $first_q_time  = strtotime(date("Y-m-d") . ' 09:44:00');     // 09:46:00

		    // 现在的时间.
		    $lottery_time = strtotime(date("Y-m-d H:i:s"));

		    if ($lottery_time < $open_time || $lottery_time > $close_time)
		    {
		        // 封盘
		        $qishu_s = -1;
		    }
		    elseif ($lottery_time < $first_q_time)
		    {
		        // 第一期
		        $qishu_s = $first_q_num;
		    }
		    else
		    {
		        // 找到最近的开奖期数.
		        $row = $d_open -> read_open();
		        if ($row)
		        {
		            // 计算期号.
		            // 小于封盘时间, 提前一分钟封盘.  300 = 5分钟
		            if ($lottery_time < (strtotime($row['time'])+300))
		            {
		                $qishu_s = $row['qihao'] + 1;
		            }
		            else
		            {
		                $qishu_s = -2;
		            }
		            
		            // $result->free();
		        }
		        else
		        {
		            $qishu_s = -1;
		        }
		    }

		    if($qishu_s == -1)
		    {
		        // 封盘
		        $result['qishu'] = $qishu_s;
		        $this -> return_data_error('-200');
		        exit;
		    }

		    if ($qishu != $qishu_s || $qishu_s == -2)
		    {
		        // 期数不对.
		        $this -> return_data_error('-201');
		        exit;
		    }
		    
		    // 2. ---------------------   判断押注的最低最高金额   ----------------------------------.
		    //判断会员账户额度是否大于总投注额度
		    //include_once("../../cache/group_".@$_SESSION["gid"].".php"); //加载权限组权限
		    //$cp_zd = @$mgk3_db['彩票最低'];
		    //$cp_zg = @$mgk3_db['彩票最高'];

		    //$cp_1q_zg = @$mgk3_db['彩票每期最高'];

		    // 最高 最低 押注.
		    $row = $g_up_limit -> read_up_limit();
		    if ($row)
		    {
		        $cp_zd = $row['cp_zd'];
		        $cp_zg = $row['cp_zg'];
		        $cp_1q_zg = $row['cp_1q_zg'];
		    }

		    if ($cp_zd > 0) {
		        $cp_zd = $cp_zd;
		    } else {
		        $cp_zd = 1;
		    }
		    if ($cp_zg > 0) {
		        $cp_zg = $cp_zg;
		    } else {
		        $cp_zg = 500;
		    }
		    
		    if ($cp_1q_zg > 0) {
		        $cp_1q_zg = $cp_1q_zg;
		    } else {
		        $cp_1q_zg = 1000;
		    }

		    // -------------------------------  循环检查每一注单的最低最高下注金额, 总下注金额.   ---------------------------
		    $allmoney = 0;
		    for ($i = 0; $i < count($list); $i++)
		    {   //检查单注金额
		        if ($names[$i] != 'autoInput')
		        {
		            $allmoney += abs($list[''.$names[$i].'']);

		            if(abs($list[''.$names[$i].'']) == 0)
		            {
		            	// 下注金额非法
		                $this -> return_data_error('-202');
		                exit; 
		            } 
		            else if (abs($list[''.$names[$i].'']) < $cp_zd) 
		            {
		            	// 低于最低下注金额.
		                $this -> return_data_error('-203');
		                exit; 
		            } 
		            else if (abs($list[''.$names[$i].'']) > $cp_zg) 
		            {
		            	// 高于最高下注金额.
		                $this -> return_data_error('-204');
		                exit; 
		            }
		        }
		    }

		    // 下注总金额. -------------------  单期下注总金额  -----------------------
		    if ($allmoney > $cp_1q_zg)
		    {
		        // 总下注金额.
		        $this -> return_data_error('-206');
		        // $msg = "每期下注总金额不能高于：￥ $cp_1q_zg";
		        exit; 
		    }

		    // 3, ----------------------------------  循环进行下注操作.  ----------------------------------
		    for ($i = 0; $i < count($list); $i++)
		    {
		        //分割键名，取ball_后的数字，来判断属于第几球
		        
		        //print_r($ball_name); ,  
		        $qiu = explode("_",$names[$i]);

		        // ----------------------------  账户余额.  ----------------------------------
		        $money  = abs($list[''.$names[$i].'']);

		        //print_r($qiu);
		        
		        // 3.1 玩法.  -------------------------  根据玩法来读上下限  ---------------------------------
		        $wanfa = $ball_name['qiu_'.$qiu[1]];
		        $wanfa_xx = $ball_name['ball_'.$qiu[1].'_'.$qiu[2]];
		        
		        //  所有人的总上下限.   -------------------------------		        
		        //  下注上限
	            $betlimit = $d_up_limit -> reat_up_limit("ball_" . $qiu[1], $qiu[2]);

		            // 每一种玩法都要检查下注是否超限.
		            $betmoney = $d_bet -> cal_money_of_wanfa($game_name, $qishu_s, $wanfa, $wanfa_xx);
		            $betmoney += $money;

		            if ($betmoney > $betlimit)
		            {
		            	// 自定义错误.
		                $msg = $wanfa . "[" . $wanfa_xx . "]" . "本期累计下注已超出限额：￥ $betlimit";
		                $this -> return_data_error_of_text('-205', $msg);
		                exit;
		            }

		            // 单个人的上下限.   --------------------------------------		            
		            // 单个玩家可以压总上限的 1/10.
		            $ubetlimit = $betlimit / 10;

		            $ubetmoney = $d_bet -> cal_money_of_wanfa_of_user($uid, $game_name, $qishu_s, $wanfa, $wanfa_xx);
		            $ubetmoney += $money;

		            if ($ubetmoney > $ubetlimit)
		            {
		            	// 自定义错误.
		                $msg = $wanfa . "[" . $wanfa_xx . "]" . "您本期累计下注已超出限额：￥ $ubetlimit";
		                $this -> return_data_error_of_text('-205', $msg);
		                exit;
		            }
		        
		        //==============返水开始============ ???????????????????????????
		        // $sql_f  =   "select cpfsbl from k_group where id='".$_SESSION["gid"]."' limit 1";
		        // $query_f    =   $mysqli->query($sql_f);
		        // $rows_f =   $query_f->fetch_array();
		        // $cpfsbl=$rows_f["cpfsbl"];
		        // if(!is_numeric($cpfsbl))$cpfsbl=0;
		        // $fs=$money*$cpfsbl;
		        //==============返水结束============ ?????????????????????????????????

		        // 3.2 玩家余额计算. ------------------------------------------
		        // k_user 存入的是玩家剩余金额. 减少.		        
		        $fs = 0;
		        $edu = $d_cost_money -> cost_money($username, $money, $fs);
		        if($edu==-1){
		        	//  ----------------- 账户余额不足 ------------------------
		            $this -> return_data_error('-7');
		            exit;
		        }

		        // 3.3 下注信息存入数据库. -----------------------------------------------
		        // 获取赔率 ---------------------------
		        $odds   = $d_odds -> read_odds ('ball_'.$qiu[1], $qiu[2]);

		        //  ----------------------  单注存入数据库.   --------------------------------------
		        $d_bet -> add_bet($qishu_s, $uid, $username, date("Y-m-d H:i:s",time()), $game_name, $qishu_s, $wanfa, $wanfa_xx, $odds, $money, $money*$odds,0,date("Y-m-d",time()),null,$fs);

		        // 错误检测.
		        // ...
		        // ...

		        $resultList[] = array('wanfa' => $wanfa,
					'wanfa_xx' => $wanfa_xx,
					'money' => $money,
					'odds' => $odds,
					'win' => $money * $odds);
		        
		        // 期号简单数字.
		        $qishu_short = substr($qishu_s, -3);

				// 总金额.		        
		        $allmoney += $money;
		    }
		}

		// 花钱历史记录要加上. 有投注历史记录作为补充.
		// ...
		// ...

		$result['allmoney'] = $allmoney;
		$result['resultList'] = $resultList;

		$this -> return_data($result);
		
	}

	
}